/*!
 Temelia - Trie tree performance tests.

 Copyright (C) 2008 Ceata (http://cod.ceata.org/proiecte/temelia).

 @author Dascalu Laurentiu

 This program is free software; you can redistribute it and
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 3
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include "include/performance.hpp"
#include "include/testutil.hpp"

extern "C"
{
#include <temelia/trie_tree.h>
}

#define MAX_WORDS_NUMBER   (10000000)
#define MAX_WORD_LENGTH          (10)

static char cuvinte[MAX_WORDS_NUMBER][MAX_WORD_LENGTH + 1];

static void generate_random_string(int id, int length)
{
	for (int i = 0; i < length; i++)
		cuvinte[id][i] = 'a' + rand() % 26;
}

static void init()
{
	memset(cuvinte, 0, sizeof(cuvinte));

	for (int i = 0; i < MAX_WORDS_NUMBER; i++)
		::generate_random_string(i, rand() % MAX_WORD_LENGTH + 1);
}

static void debug(bool force = false)
{
	if (!force)
		return;

	for (int i = 0; i < MAX_WORDS_NUMBER; i++)
		printf("%s\n", cuvinte[i]);
}

static trie_tree_t __temelia_trie_tree_insert(int n)
{
	trie_tree_t trie_tree;

	trie_tree = trie_new(NULL);

	for (int i = 0; i < n && i < MAX_WORDS_NUMBER; i++)
		trie_insert(trie_tree, cuvinte[i], default_collection[i]);

	return trie_tree;
}

static void temelia_trie_tree_insert(int n)
{
	trie_delete(__temelia_trie_tree_insert(n));
}

static void temelia_trie_tree_search(int n)
{
	trie_tree_t trie_tree;

	trie_tree = __temelia_trie_tree_insert(n);

	for (int i = 0; i < n && i < MAX_WORDS_NUMBER; i++)
		trie_search(trie_tree, cuvinte[i]);

	trie_delete(trie_tree);
}

static void temelia_trie_tree_remove(int n)
{
	trie_tree_t trie_tree;

	trie_tree = __temelia_trie_tree_insert(n);

	for (int i = 0; i < n && i < MAX_WORDS_NUMBER; i++)
		trie_remove(trie_tree, cuvinte[i]);

	trie_delete(trie_tree);
}

void TemeliaPerformance::pt_trie(void)
{
	TestUnit testUnit("trie_tree");
	::init();
	::debug();

	GENERATE_TEMELIA_TEST(testUnit, "insert", trie_tree_insert);
	GENERATE_TEMELIA_TEST(testUnit, "search", trie_tree_search);
	GENERATE_TEMELIA_TEST(testUnit, "remove", trie_tree_remove);

	testUnit.write(fout);
}
